<template>
  <view class="container">
    <!-- 标题 -->
    <view class="header">
      <view class="title">任务完成度统计</view>
      <view class="subtitle">各任务类别完成情况统计</view>
    </view>
    
    <!-- 时间筛选 -->
    <view class="filter-section">
      <picker 
        mode="selector" 
        :range="dateRangeOptions" 
        range-key="name" 
        @change="onDateRangeChange"
      >
        <view class="picker-btn">
          <uni-icons type="calendar" size="20" color="#4A9AFF"></uni-icons>
          <text>{{ selectedRange.name }}</text>
          <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
        </view>
      </picker>
    </view>
    
    <!-- 柱状图容器 -->
    <view class="chart-container">
      <qiun-data-charts
        type="column"
        :opts="chartOptions"
        :chartData="chartData"
        canvasId="taskChart"
        canvas2d
      />
    </view>
    
    <!-- 导出按钮 -->
    <view class="export-btn-container">
      <button class="export-btn" @click="exportData">
        <uni-icons type="download-filled" size="22" color="#FFFFFF"></uni-icons>
        <text>导出报表</text>
      </button>
    </view>
    
    <!-- 底部信息 -->
    <view class="footer">
      <text>数据更新于: {{ currentDate }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 日期范围选项
      dateRangeOptions: [
        { name: '本周', value: 'week' },
        { name: '本月', value: 'month' },
        { name: '本季度', value: 'quarter' },
        { name: '本年度', value: 'year' }
      ],
      selectedRange: { name: '本月', value: 'month' },
      
      // 图表数据
      chartData: {},
      
      // 图表配置
      chartOptions: {
        padding: [20, 15, 15, 15],
        enableScroll: false,
        legend: {
          show: false
        },
        xAxis: {
          disableGrid: true,
          fontColor: '#666',
          rotateLabel: false
        },
        yAxis: {
          disabled: false,
          gridType: 'dash',
          dashLength: 2,
          gridColor: '#F0F0F0',
          fontColor: '#999',
          max: 100,
          min: 0,
          splitNumber: 5,
          format: val => val + '%'
        },
        extra: {
          column: {
            type: 'group',
            width: 30,
            activeBgColor: '#000000',
            activeBgOpacity: 0.08,
            linearType: 'custom'
          }
        },
        animation: true
      },
      
      // 当前日期
      currentDate: this.$dayjs().format('YYYY-MM-DD HH:mm')
    }
  },
  
  created() {
    // 初始化图表数据
    this.initChartData()
  },
  
  methods: {
    // 初始化图表数据
    initChartData() {
      let categories = []
      let series = []
      
      // 根据选择的时间范围获取不同数据
      switch (this.selectedRange.value) {
        case 'week':
          categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          series = [
            { name: '完成度', data: [78, 85, 92, 88, 95, 62, 75] }
          ]
          break;
        case 'month':
          categories = ['项目开发', '技术支持', '文档撰写', '会议沟通', '培训学习']
          series = [
            { name: '完成度', data: [85, 75, 92, 68, 80] }
          ]
          break;
        case 'quarter':
          categories = ['Q1季度', 'Q2季度', 'Q3季度', 'Q4季度']
          series = [
            { name: '完成度', data: [75, 88, 79, 92] }
          ]
          break;
        case 'year':
          categories = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
          series = [
            { name: '完成度', data: [75, 82, 78, 85, 90, 88, 92, 86, 84, 89, 91, 93] }
          ]
          break;
      }
      
      // 设置柱状图颜色（根据完成度渐变）
      series.forEach(item => {
        item.data.forEach((value, index) => {
          item.color = this.getColor(value)
        })
      })
      
      // 构建图表数据对象
      this.chartData = {
        categories: categories,
        series: series
      }
    },
    
    // 根据完成度获取颜色
    getColor(value) {
      if (value >= 90) return '#3BA272'
      if (value >= 80) return '#4A9AFF'
      if (value >= 70) return '#9B6DEA'
      if (value >= 60) return '#FFA54F'
      return '#FF6B6B'
    },
    
    // 时间范围改变事件
    onDateRangeChange(e) {
      this.selectedRange = this.dateRangeOptions[e.detail.value]
      this.initChartData()
    },
    
    // 导出数据
    exportData() {
      uni.showLoading({
        title: '正在导出...'
      })
      
      // 模拟导出操作
      setTimeout(() => {
        uni.hideLoading()
        uni.showToast({
          title: '导出成功',
          icon: 'success'
        })
        
        // 实际项目中此处调用导出API
        // 下面是H5端的导出实现示例
        if (process.env.VUE_APP_PLATFORM === 'h5') {
          this.exportCSV()
        } else {
          this.showExportSuccess()
        }
      }, 1500)
    },
    
    // (H5端)CSV导出
    exportCSV() {
      const rows = this.chartData.categories.map((category, index) => {
        return `${category},${this.chartData.series[0].data[index]}%`
      })
      
      const csvContent = '类别,完成度\n' + rows.join('\n')
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      
      link.setAttribute('href', url)
      link.setAttribute('download', `任务完成度统计_${this.selectedRange.name}_${this.$dayjs().format('YYYYMMDD')}.csv`)
      link.style.visibility = 'hidden'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    
    // (非H5端)显示导出成功提示
    showExportSuccess() {
      uni.showModal({
        title: '导出成功',
        content: `报表已成功保存到设备中，路径：任务完成度统计_${this.selectedRange.name}.csv`,
        showCancel: false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f8f9fb;
  min-height: 100vh;
  padding: 40rpx;
  display: flex;
  flex-direction: column;
}

.header {
  text-align: center;
  margin-bottom: 50rpx;
  
  .title {
    font-size: 42rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: #999;
  }
}

.filter-section {
  margin-bottom: 30rpx;
  display: flex;
  justify-content: center;
  
  .picker-btn {
    background: white;
    border-radius: 50rpx;
    padding: 16rpx 36rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    
    text {
      margin: 0 12rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
}

.chart-container {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 40rpx;
  height: 550rpx;
}

.export-btn-container {
  margin: 30rpx 0;
  
  .export-btn {
    background: linear-gradient(to right, #4A9AFF, #3A7AE9);
    color: white;
    border-radius: 50rpx;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10rpx;
    box-shadow: 0 8rpx 25rpx rgba(74, 154, 255, 0.3);
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.98);
    }
  }
}

.footer {
  text-align: center;
  font-size: 26rpx;
  color: #999;
  margin-top: 40rpx;
}
</style>